package org.bpms.interceptor;

import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.bpms.model.admin.Member;
import org.bpms.model.wechat.Weixin;
import org.bpms.plugins.bjui.BjuiRender;
import org.bpms.service.admin.MemberService;
import org.bpms.service.wechat.WeixinService;

import com.jfinal.aop.Enhancer;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.JFinal;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.JsTicket;
import com.jfinal.weixin.sdk.api.JsTicketApi;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.JsTicketApi.JsApiType;

/**
 * 前台全局拦截器
 * @author hupei
 *
 */
public class WebInterceptor  implements Interceptor {
	private WeixinService weixinService = Enhancer.enhance(WeixinService.class);
	private MemberService memberService = Enhancer.enhance(MemberService.class);

	@Override
	public void intercept(Invocation ai) {
		Map<String, String> _wxMap = ai.getController().getSessionAttr("_wxMap");
		ApiConfigKit.setThreadLocalApiConfig(getApiConfig());
		Member member = ai.getController().getSessionAttr("member");
		if (null == member){
			if (ai.getActionKey().equals("/wechatapi/exturl")){
				ai.invoke();
			}else{
				String code = ai.getController().getPara("code" , "");
				ApiConfigKit.setThreadLocalApiConfig(getApiConfig());
				SnsAccessToken snsAccessToken = 
						SnsAccessTokenApi.getSnsAccessToken(ApiConfigKit.getApiConfig().getAppId(),
								ApiConfigKit.getApiConfig().getAppSecret(), code);
				if (null == snsAccessToken){
					ai.getController().render("/web/follow.html");
				}else{
					String openid = snsAccessToken.getOpenid();
					member = memberService.findById(openid);
					if (null == member){
						System.out.println("空.........................");
						ai.getController().render("/web/follow.html");
					}else{
						ai.getController().setSessionAttr("member", member);
						ai.invoke();
					}
				}
			}
		}else{			
			if(!JFinal.me().getConstants().getDevMode()){
				//异常集中返回json
				try {
					ai.invoke();
				} catch (RuntimeException e) {
					//最多处理10次嵌套查询原始出错信息
					Throwable t = e.getCause();
					for (int i = 0; i < 10; i++) {
						if(StringUtils.isNotBlank(t.getMessage())){
							ai.getController().render(BjuiRender.error(t.getMessage()));
							return;
						}
						t = t.getCause();
					}
					throw new RuntimeException(e);
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}else{
				ai.invoke();
			}			
		}	
	}
	
	public ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();
		Prop p = PropKit.use("config.properties");
		Weixin weixin = weixinService.find();
		if (null != weixin){
			// 配置微信 API 相关常量
			ac.setAppId(weixin.getStr("appid"));
			ac.setAppSecret(weixin.getStr("appsecret"));
			ac.setToken(weixin.getStr("token"));
			if (null != weixin.getStr("encodingaeskey") && !weixin.getStr("encodingaeskey").equals("")){
				ac.setEncryptMessage(true);
				ac.setEncodingAesKey(weixin.getStr("encodingaeskey"));
			}
			if (p.getBoolean("redis_mode")){
				ac.setIsredis(true);
			}
			return ac;
		}
		return null;
	}
}
